from django.shortcuts import render

from goods.models import Goods, GoodsCategory




def index(request):
    if request.method == 'GET':
        goods_dict = {}
        goods = Goods.objects.all()
        categorys = GoodsCategory.CATEGORY_TYPE
        for category in categorys:
            goods_list = []
            count = 0
            for good in goods:
                # 判断商品分类和商品对象
                if count < 4:
                    if category[0] == good.category_id:
                        goods_list.append(good)
                        count += 1
            # {'新鲜水果'：[],}
            goods_dict[category[1]] = goods_list
        return render(request,'index.html',{'goods_dict':goods_dict})




def detail(request,id):
    if request.method == 'GET':
        # 查看商品详情，返回商品对象
        goods = Goods.objects.filter(pk=id).first()
        # 所有商品的种类
        categorys = GoodsCategory.CATEGORY_TYPE
        # 当前商品对应的种类
        category = goods.category
        # 当前商品的种类在GoodsCategory对应的元素，是一个数字
        count = category.category_type
        # 当前商品所属类型的名字
        category_name = categorys[count-1][1]
        number = 1
        # session中保存的商品数量
        session_goods = request.session.get('goods')
        if session_goods:
            for good in session_goods:
                if int(good[0]) == int(id):
                    number = int(good[1])
                    break
        return render(request,'detail.html',{'goods':goods,'number':number,'category_name':category_name})

def list(request):
    if request.method == 'GET':
        return render(request,'list.html')

